package com.zhujiaji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhujiaji.common.Result;
import com.zhujiaji.common.UserThreadLocal;
import com.zhujiaji.mapper.UserMapper;
import com.zhujiaji.pojo.Role;
import com.zhujiaji.pojo.User;
import com.zhujiaji.service.RedisService;
import com.zhujiaji.service.UserService;
import com.zhujiaji.util.JwtUtil;
import com.zhujiaji.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱佳吉
 * @date 2024/3/16 21:22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisService redisService;

    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Objects.nonNull(user.getUsername()), User::getUsername, user.getUsername());
        User result = baseMapper.selectOne(wrapper);
        if (result == null) {
            return Result.error("账号或密码错误");
        }

        String password = result.getPassword();
        if (!result.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))) {
            return Result.error("账号或密码错误");
        }

        // 登录成功

        // 需要jwt生成token, 存到redis
        String token = JwtUtil.generatorToken(result.getId());
        redisService.setString("token_", token, 30, TimeUnit.MINUTES);

        // 把用户id存到ThreadLocal
        UserThreadLocal.put(result);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    @Override
    public Result getInfo(String token) {
        String redisToken = redisService.getString("token_");
        if (redisToken == null) {
            return Result.error("没登入");
        }

        Integer userId = JwtUtil.parseToken(redisToken);
        if (userId == null) {
            return Result.error("token失效");
        }

        User user = baseMapper.selectById(userId);
        if (user == null) {
            Result.error("token错误");
        }

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        // 拿角色
        List<String> roles = baseMapper.selectRolesById(userVo.getId());

        userVo.setRoles(roles);
        return Result.ok(userVo);
    }
}
